package com.lngsyz.file.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.json.JSONObject;

@SuppressWarnings("deprecation")
public class HttpUtils {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);
	
	/**
	 * get
	 * 
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @return
	 * @throws Exception
	 */
	public static String doGet(String host, String path, 
			Map<String, String> headers, 
			Map<String, String> querys)
            throws Exception {    	
		CloseableHttpClient httpClient = wrapClient(host);
		String resultString = "";
		CloseableHttpResponse response = null;
		HttpGet request = null;
		try {
	    	request = new HttpGet(buildUrl(host, path, querys));
	    	if(headers != null) {
	    		for (Map.Entry<String, String> e : headers.entrySet()) {
	    			request.addHeader(e.getKey(), e.getValue());
	    		}
	    	}
	        response = httpClient.execute(request);
	        if(response != null) {
	        	// 判断返回状态是否为200
		        if (response.getStatusLine().getStatusCode() == 200) {
	            	// 获取响应对象
	    			HttpEntity resEntity = response.getEntity();
	            	resultString = EntityUtils.toString(response.getEntity(), "utf-8");
	            	System.out.println(resultString);
	            	// 销毁
	    			EntityUtils.consume(resEntity);
		        }
            }
		} catch (Exception e) {
            LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
        } finally {
        	try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
			}
			try {
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
			}
        }
        return resultString;
    }
	
	public static String doGet(String url, ResponseHandler<String> responseHandler)
            throws Exception {    	
		CloseableHttpClient httpClient = wrapClient(url);
		String response = "";
		// CloseableHttpResponse response = null;
		HttpGet request = null;
		try {
	    	request = new HttpGet(url);
	        response = httpClient.execute(request, responseHandler);
	        return response;
		} catch (Exception e) {
            LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
        } finally {
			try {
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
			}
        }
        return response;
    }
	
	/**
     * httpGet请求
     */
    public static com.alibaba.fastjson.JSONObject doGet(String url) {
        // get请求返回结果
    	com.alibaba.fastjson.JSONObject jsonResult = null;
        HttpClient client = CertificateValidationIgnored.getNoCertificateHttpClient(null);
        // 发送get请求
        HttpGet request = new HttpGet(url);
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
        request.setConfig(requestConfig);
        try {
            HttpResponse response = client.execute(request);
            // 请求发送成功，并得到响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                HttpEntity entity = response.getEntity();
                String strResult = EntityUtils.toString(entity, "utf-8");
                // 把json字符串转换成json对象
                jsonResult = com.alibaba.fastjson.JSONObject.parseObject(strResult);
            } else {
            	LOGGER.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
        } finally {
            request.releaseConnection();
        }
        return jsonResult;
    }
	
	/**
	 * post form
	 * 
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @param bodys
	 * @return
	 * @throws Exception
	 */
	public static String doPost(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys, 
			Map<String, String> bodys)
            throws Exception {    	
		// 创建Httpclient对象
        CloseableHttpClient httpClient = wrapClient(host);
        CloseableHttpResponse response = null;
        String resultString = "";
        HttpPost request = null;
        try {
        	request = new HttpPost(buildUrl(host, path, querys));
            for (Map.Entry<String, String> e : headers.entrySet()) {
            	request.addHeader(e.getKey(), e.getValue());
            }

            if (bodys != null) {
                List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

                for (String key : bodys.keySet()) {
                    nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
                }
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
                formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
                request.setEntity(formEntity);
            }
            response = httpClient.execute(request);
            if(response != null) {
            	// 获取响应对象
    			HttpEntity resEntity = response.getEntity();
            	resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            	System.out.println(resultString);
            	// 销毁
    			EntityUtils.consume(resEntity);
            }
        } catch (Exception e) {
            LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
        } finally {
        	try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
			}
			try {
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
			}
        }

        return resultString;
    }	
	
	/**
	 * post form
	 * 
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @param bodys
	 * @return
	 * @throws Exception
	 */
//	public static String doPostForIaip(String host, String path, String param) throws Exception {    	
//		// 创建Httpclient对象
//        CloseableHttpClient httpClient = wrapClient(host);
//        CloseableHttpResponse response = null;
//        String resultString = "";
//        try {
//			HttpPost httppost = new HttpPost(host + path);
//			if(param != null && !param.trim().equals("")) {
//				StringEntity strEntity = new StringEntity(param, "UTF-8");
//				httppost.addHeader("content-type", "application/json");
//				httppost.setEntity(strEntity);
//			}
//			//设置超时时间
//			RequestConfig requestConfig = RequestConfig.custom()  
//			        .setConnectTimeout(5000).setConnectionRequestTimeout(1000)  
//			        .setSocketTimeout(5000).build();
//			httppost.setConfig(requestConfig);
//			response = httpClient.execute(httppost);
//            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
//            System.out.println(resultString);
//        } catch (Exception e) {
//            LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
//        } finally {
//            try {
//            	if(response != null) {
//            		response.close();
//            	}
//            } catch (IOException e) {
//                // TODO Auto-generated catch block
//                LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
//            }
//        }
//
//        return resultString;
//	}
	
	public static String doPostForIaip(String host, String path, String param) throws Exception {    	
		// 创建Httpclient对象
        CloseableHttpClient httpClient = wrapClient(host);
        CloseableHttpResponse response = null;
        String resultString = "";
        HttpPost httppost = null;
        try {
        	httppost = new HttpPost(host + path);
			if(param != null && !param.trim().equals("")) {
				StringEntity strEntity = new StringEntity(param, "UTF-8");
				httppost.addHeader("content-type", "application/json");
				httppost.setEntity(strEntity);
			}
			//设置超时时间
			RequestConfig requestConfig = RequestConfig.custom()  
			        .setConnectTimeout(5000).setConnectionRequestTimeout(1000)  
			        .setSocketTimeout(5000).build();
			httppost.setConfig(requestConfig);
			response = httpClient.execute(httppost);
			if(response != null) {
            	// 获取响应对象
    			HttpEntity resEntity = response.getEntity();
            	resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            	// System.out.println(resultString);
            	// 销毁
    			EntityUtils.consume(resEntity);
            }
        } catch (Exception e) {
            LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
        } finally {
        	try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
			}
			try {
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
			}
        }

        return resultString;
	}
	
	public static String doPostForIaip(String url, String param) throws Exception {    	
		// 创建Httpclient对象
		CloseableHttpClient httpClient = wrapClient(url);
		CloseableHttpResponse response = null;
		String resultString = "";
		HttpPost httppost = null;
		try {
			httppost = new HttpPost(url);
			if(StringUtils.isNotBlank(param)) {
				StringEntity strEntity = new StringEntity(param, "UTF-8");
				httppost.addHeader("content-type", "application/json");
				httppost.setEntity(strEntity);
			}
			//设置超时时间
			RequestConfig requestConfig = RequestConfig.custom()  
					.setConnectTimeout(5000).setConnectionRequestTimeout(1000)  
					.setSocketTimeout(5000).build();
			httppost.setConfig(requestConfig);
			response = httpClient.execute(httppost);
			if(response != null) {
				// 获取响应对象
				HttpEntity resEntity = response.getEntity();
				resultString = EntityUtils.toString(response.getEntity(), "utf-8");
				System.out.println(resultString);
				// 销毁
				EntityUtils.consume(resEntity);
			}
		} catch (Exception e) {
			LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
		} finally {
			try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
			}
			try {
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
			}
		}
		
		return resultString;
	}
	
	/**
	 * post form
	 * 
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @param bodys
	 * @return
	 * @throws Exception
	 */
	public static String doPost(String host, String path,
			// String method, 
			Map<String, String> headers, 
			// Map<String, String> querys, 
			JSONObject bodys) throws Exception {    	
		// 创建Httpclient对象
        CloseableHttpClient httpClient = wrapClient(host);
        CloseableHttpResponse response = null;
        String resultString = "";
        HttpPost request = null;
        try {
		
			request = new HttpPost(buildUrl(host, path, new HashMap<String, String>()));
			if(headers != null) {
				for (Map.Entry<String, String> e : headers.entrySet()) {
					request.addHeader(e.getKey(), e.getValue());
				}
			}
			
			if (bodys != null) {
				ByteArrayEntity entity = null;
				try {
					entity = new ByteArrayEntity(bodys.toString().getBytes("UTF-8"));
					entity.setContentType("application/json");
				} catch (UnsupportedEncodingException e) {
					LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
					throw new RuntimeException("向服务器承保接口发起http请求,封装请求body时出现异常", e);
				}
				request.setEntity(entity);
			}
			//设置超时时间
//			RequestConfig requestConfig = RequestConfig.custom()  
//			        .setConnectTimeout(5000).setConnectionRequestTimeout(1000)  
//			        .setSocketTimeout(5000).build();
//			request.setConfig(requestConfig);
			// 执行http请求
            response = httpClient.execute(request);
            if(response != null) {
            	// 获取响应对象
    			HttpEntity resEntity = response.getEntity();
            	resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            	System.out.println(resultString);
            	// 销毁
    			EntityUtils.consume(resEntity);
            }
        } catch (Exception e) {
            LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
        } finally {
        	try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
			}
			try {
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
			}
        }

        return resultString;
	}	
	
	/**
	 * Post String
	 * 
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @param body
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doPost(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys, 
			String body)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
        	request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }
	
	/**
	 * Post stream
	 * 
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @param body
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doPost(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys, 
			byte[] body)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
        	request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }
	
	/**
	 * Put String
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @param body
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doPut(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys, 
			String body)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
        	request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }
	
	/**
	 * Put stream
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @param body
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doPut(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys, 
			byte[] body)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
        	request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }
	
	/**
	 * Delete
	 *  
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doDelete(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }
        
        return httpClient.execute(request);
    }
	
	public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = wrapClient(url);
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
            }
        }
        return resultString;
    }
	
	public static String doPostForm(String host, List<File> files, Map<String, String> headers, Map<String, String> params) throws Exception {    	
		// 创建Httpclient对象
        CloseableHttpClient httpClient = wrapClient(host);
        CloseableHttpResponse response = null;
        String resultString = "";
        HttpPost httpPost = null;
        try {
        	httpPost = new HttpPost(host);
            for (Map.Entry<String, String> e : headers.entrySet()) {
            	httpPost.addHeader(e.getKey(), e.getValue());
            }
           MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            if (files != null) {
				for (File file : files) {
					builder.addBinaryBody("file", new FileInputStream(file), ContentType.DEFAULT_BINARY, file.getName());
				}
			}
            if (params != null) {
            	for (Map.Entry<String, String> entry : params.entrySet()) {
					String key = entry.getKey();
					// 相当于<input type="text" name="userName" value=userName>
					if(StringUtils.isNotBlank(entry.getValue())) {
						StringBody value = new StringBody(entry.getValue(), ContentType.create("text/plain", Consts.UTF_8));
						builder.addPart(key, value);
					}
				}
            }
            HttpEntity reqEntity = builder.build();
			httpPost.setEntity(reqEntity);
            response = httpClient.execute(httpPost);
            if(response != null) {
            	// 获取响应对象
    			HttpEntity resEntity = response.getEntity();
            	resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            	// System.out.println(resultString);
            	// 销毁
    			EntityUtils.consume(resEntity);
            }
        } catch (Exception e) {
            LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
        } finally {
        	try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
			}
			try {
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
			}
        }

        return resultString;
    }
	
	private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
    	StringBuilder sbUrl = new StringBuilder();
    	sbUrl.append(host);
    	if (!StringUtils.isBlank(path)) {
    		sbUrl.append(path);
        }
    	if (null != querys) {
    		StringBuilder sbQuery = new StringBuilder();
        	for (Map.Entry<String, String> query : querys.entrySet()) {
        		if (0 < sbQuery.length()) {
        			sbQuery.append("&");
        		}
        		if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
        			sbQuery.append(query.getValue());
                }
        		if (!StringUtils.isBlank(query.getKey())) {
        			sbQuery.append(query.getKey());
        			if (!StringUtils.isBlank(query.getValue())) {
        				sbQuery.append("=");
        				sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
        			}        			
                }
        	}
        	if (0 < sbQuery.length()) {
        		sbUrl.append("?").append(sbQuery);
        	}
        }
    	
    	return sbUrl.toString();
    }
	
	private static CloseableHttpClient wrapClient(String host) {
		CloseableHttpClient httpClient = new DefaultHttpClient();
		if (host.startsWith("https://")) {
			sslClient(httpClient);
		}
		
		return httpClient;
	}
	
	private static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] xcs, String str) {
                	
                }
                public void checkServerTrusted(X509Certificate[] xcs, String str) {
                	
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (KeyManagementException e) {
        	LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
        	LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
        	throw new RuntimeException(e);
        }
    }

	@SuppressWarnings("resource")
	public static HttpResponse request(String host, String path, JSONObject jo) {
		//请求的body信息
		String requestBody = jo.toString();
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(host+path);
		//添加header
		//添加body
		ByteArrayEntity entity = null;
		try {
			entity = new ByteArrayEntity(requestBody.getBytes("UTF-8"));
			entity.setContentType("application/json");
		} catch (UnsupportedEncodingException e) {
			LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
			throw new RuntimeException("向服务器承保接口发起http请求,封装请求body时出现异常", e);
		}
		httpPost.setEntity(entity);
		//执行post请求
		HttpResponse response = null;
		try {
			response = httpClient.execute(httpPost);
		} catch (ClientProtocolException e) {
			LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
			throw new RuntimeException("提交给服务器的请求，不符合HTTP协议", e);
		} catch (IOException e) {
			LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
			throw new RuntimeException("向服务器承保接口发起http请求,执行post请求异常", e);
		}
		return response;
	}
	
	public static byte[] download(String url) {
		byte[] rtn = null;
		try {
			// 创建Httpclient对象
	        CloseableHttpClient client = wrapClient(url);
			HttpGet httpget = new HttpGet(url);
			HttpResponse response = client.execute(httpget);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            rtn = outputStream.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rtn;
	}
	
	public static void main(String args[]) {
		String host = "https://218.60.149.205:80/";
		String path = "v1/ywtb/add";
		Map<String, String> headers = new HashMap<String, String>();
		JSONObject bodys = new JSONObject();
		bodys = JSONObject.fromObject("{\"ESeal\":\"\",\"address\":\"辽宁省大连市甘井子区辛博西园107号1单元13层2号\",\"apCertNo\":\"210202196403055445\",\"apCertType\":\"10\",\"apName\":\"张玉勤\",\"apPhone\":\"\",\"businessId\":\"210211001012020121088261\",\"companyId\":\"ccccb47890d64c5d8589aec9bdc11177\",\"createDate\":\"2024-02-07 09:29:41\",\"crpCertNo\":\"210202196403055445\",\"crpCertType\":\"10\",\"crpName\":\"张玉勤\",\"crpPhone\":\"13164524756\",\"deliveryMethod\":\"1\",\"districtCode\":\"210211\",\"gov\":\"2\",\"id\":\"a0aee328d88d4c0ebefb8894888a5757\",\"instCode\":\"91210211MA10TNLN1A\",\"name\":\"佳玉天泽文化传媒发展（大连市）有限责任公司\",\"pripid\":\"210211001012020121088261\",\"receiveAddress\":\"\",\"receiveCertNo\":\"\",\"receiveCertType\":\"10\",\"receiveName\":\"\",\"receivePhone\":\"\",\"seals\":[{\"price\":0.02,\"referSealId\":\"96942a80492c44afbc0de46d05203031\",\"sealId\":\"a722090607e7487aaeda90ca1d384a94\",\"sealMaterial\":\"01\",\"sealMedia\":\"3\",\"sealType\":\"05\"}],\"tax\":\"\",\"tradeNo\":\"\",\"zfsj\":\"\"}");
		try {
			HttpUtils.doPost(host, path, headers, bodys);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}